package com.mytest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.mytest.bean.UserBean;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @author jzs created 2017/5/8
 *         RxJava测试
 */
public class RxAndroidActivity extends AppCompatActivity {
    public static final String TAG = "RxAndroidActivity";

    List<String> mList = new ArrayList<>();
    List<UserBean> mUserList = new ArrayList<>();
    @BindView(R.id.tv)
    TextView tv;

    @OnClick(R.id.btn)
    void btn() {
        printCourseFlatMap();
    }

    @OnClick(R.id.btn_spring)
    void btn_spring() {
        startActivity(new Intent(RxAndroidActivity.this, TransActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_android);
        ButterKnife.bind(this);
        for (int i = 0; i < 11; i++) {
            mList.add(i + "");
        }
        for (int i = 0; i < 10; i++) {
            UserBean userBean = new UserBean();
            userBean.name = "学生" + i;
            userBean.userAge = i;
            for (int j = 0; j < i; j++) {
                userBean.course.add("课程" + j);
            }
            mUserList.add(userBean);
        }
    }


    /**
     * @author jzs created 2017/5/9
     * 创建observer
     */
    private Observer<String> observer() {
        Observer<String> observer = new Observer<String>() {

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                Log.e("sk", "onNext: " + s);
            }
        };
        return observer;
    }

    /**
     * @author jzs created 2017/5/9
     * 创建subscriber
     * <p>
     * RxJava 还内置了一个实现了 Observer 的抽象类：Subscriber。 Subscriber 对 Observer 接口进行了一些扩展，但他们的基本使用方式是完全一样的
     * 实质上，在 RxJava 的 subscribe 过程中，Observer 也总是会先被转换成一个 Subscriber 再使用
     */
    private Subscriber<String> subscriber() {
        Subscriber<String> subscriber = new Subscriber<String>() {

            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                Log.e("sk", "onNext: " + s);
            }
        };
        return subscriber;
    }

    /**
     * @author jzs created 2017/5/9
     * 创建 observable （被观察者）
     */
    private Observable observable() {
        //lambda写法
        Observable observablLambda = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("ss");
            }

        });

        Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                subscriber.onNext("Hello");
                subscriber.onNext("Hi");
                subscriber.onNext("Aloha");
                subscriber.onCompleted();
            }

        });
//        Observable observable1 = Observable.just("1", "2", "3", "4");
        return observable;
    }

    /**
     * @author jzs created 2017/5/10
     * 一般的写法
     */
    private void example() {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                for (int i = 0; i < mList.size(); i++) {
                    subscriber.onNext(mList.get(i));
                }
                subscriber.onCompleted();
            }
        })
                .subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程
                .observeOn(AndroidSchedulers.mainThread())// 指定 Subscriber 的回调发生在主线程
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {
                        Log.e("sk", "onNext: " + s);
                    }
                });
    }

    /**
     * @author jzs created 2017/5/10
     * 变换
     * FuncX 和 ActionX 的区别在 FuncX 包装的是有返回值的方法。
     */
    private void map() {
        Observable.just("5") // 输入类型 String
                .map(new Func1<String, Integer>() {
                    @Override
                    public Integer call(String str) { // 参数类型 String
                        int i = Integer.parseInt(str);
                        return i; // 返回类型 Integer
                    }
                })
                .subscribe(new Action1<Integer>() {
                    @Override
                    public void call(Integer integer) { // 参数类型 Integer
                        Log.e(TAG, "call: " + integer);
                    }
                });
    }

    /**
     * @author jzs created 2017/5/10
     * 需求：打印出所有名字
     */
    private void printName() {
        Subscriber<String> subscriber = new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                Log.e(TAG, "onNext: " + s);
                String name = tv.getText().toString() + s;
                tv.setText(name);
            }
        };

        Observable.from(mUserList).map(new Func1<UserBean, String>() {
            @Override
            public String call(UserBean userBean) {
                return userBean.name;
            }
        })
                .subscribe(subscriber);
    }

    /**
     * @author jzs created 2017/5/10
     * 需求：打印所有课程
     */
    private void printCourse() {
        Subscriber<UserBean> subscriber = new Subscriber<UserBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(UserBean s) {
                Log.e(TAG, "onNext: " + s);
                String name = tv.getText().toString() + s.name;
                String course = "";
                for (int i = 0; i < s.course.size(); i++) {
                    course = course + s.course.get(i);
                }

                tv.setText(name + ":" + course + "\n");
            }
        };

        Observable.from(mUserList).subscribe(subscriber);
    }

    /**
     * @author jzs created 2017/5/10
     * 使用flatMap打印所有课程
     */
    private void printCourseFlatMap() {
//        Subscriber<String> subscriber = new Subscriber<String>() {
//            @Override
//            public void onCompleted() {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onNext(String s) {
//                Log.e(TAG, "onNext: " + s);
//            }
//        };
        Observable.from(mUserList)
                .flatMap(new Func1<UserBean, Observable<String>>() {
                    //传入UserBean，传出course，在subscribe中获得并打印
                    @Override
                    public Observable<String> call(UserBean userBean) {
                        return Observable.from(userBean.course);
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        Log.e(TAG, "onNext: " + s);
                    }
                });
    }

    /**
     * @author jzs created 2017/5/16
     * 自定义 subscriber 方法
     */
    private void customCall() {
        Action1<String> onNextAction = new Action1<String>() {
            // onNext()
            @Override
            public void call(String s) {
                Log.d("sk", s);
            }
        };
        Action1<Throwable> onErrorAction = new Action1<Throwable>() {
            // onError()
            @Override
            public void call(Throwable throwable) {
                // Error handling
            }
        };
        Action0 onCompletedAction = new Action0() {
            // onCompleted()
            @Override
            public void call() {
                Log.d("sk", "completed");
            }
        };
        Observable observable = Observable.create(new Observable.OnSubscribe() {
            @Override
            public void call(Object o) {

            }
        });
        // 自动创建 Subscriber ，并使用 onNextAction 来定义 onNext()
        observable.subscribe(onNextAction);
        // 自动创建 Subscriber ，并使用 onNextAction 和 onErrorAction 来定义 onNext() 和 onError()
        observable.subscribe(onNextAction, onErrorAction);
        // 自动创建 Subscriber ，并使用 onNextAction、 onErrorAction 和 onCompletedAction 来定义 onNext()、 onError() 和 onCompleted()
        observable.subscribe(onNextAction, onErrorAction, onCompletedAction);
    }

}
